package cn.tedu.straw.portal.security;

import cn.tedu.straw.portal.service.IUserService;
import cn.tedu.straw.portal.vo.Permission;
import cn.tedu.straw.portal.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    IUserService userService;

  /*
    在 UserDetailsService 接口中的 loadUserByUsername()
    方法是由Spring Security框架调用的，当用户在登录页面中输入用户名、密码之后
    Spring Security就会使用用户提交的用户名来调用 loadUserByUsername()方法
    该方法应该返回与用户名匹配的用户信息，例如用户的密码等等，
    Spring Security会自动完成接下来的密码对比及授权等过程。
   */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //调用业务层根据登录时填写的手机号查询数据库中的数据
        UserLoginVo loginVo = userService.loginByPhone(s);

        //如果手机号没有对应的数据,则直接返回null,登陆失败
        if (loginVo == null){
            return null;
        }

        // 从查询结果中取出权限数据，封装为Spring Security需要的类型
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<Permission> permissions = loginVo.getPermissions();
        for (Permission permission : permissions) {
            String authority = permission.getAuthority();
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
            authorities.add(grantedAuthority);
        }

        // 创建LoginUserInfo对象，准备作为返回给Spring Security的对象
        LoginUserInfo loginUserInfo = new LoginUserInfo(
              loginVo.getPhone(),
              loginVo.getPassword(),
              loginVo.getIsEnabled() == 1,
              true,
              true,
              loginVo.getIsLocked() == 0,
               authorities
        );

        loginUserInfo.setUserId(loginVo.getId());
        loginUserInfo.setNickName(loginVo.getNickName());

        return loginUserInfo;
    }


}
